package com.example.customizedgroupmessage;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.View;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.widget.*;

import java.util.Date;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import android.text.Editable;

public class SMSTemplate extends Activity {

	public static final int REQUEST_CODE_SMSCUSTOMWORD=1004;
	public static final int REQUEST_CODE_TEMPLATEBOXACTIVITY=1005;
	public static final int REQUEST_CODE_TEMPLATECALL=1006;
	public static final int REQUEST_CODE_SMSSEND=1007;
	
	// 템플릿
	public static Template smsTemplate;
	private TextView capableByte;
	private EditText ed1; 

	DBHelper mHelper;
	SQLiteDatabase db;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_template);
		
		capableByte =(TextView)findViewById(R.id.capableByte);
		// 내용 입력 창
		ed1 =(EditText)findViewById(R.id.editText);
		// 입력 bytes 수 표시
		ed1.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {}
			@Override
			public void onTextChanged(CharSequence charSequence, int start, int before, int count) {}
			@Override
			public void afterTextChanged(Editable editable) {
				showBytes();
			}
		});
		
		// sms Template db 생성
		mHelper = new DBHelper(this);
		
		// 템플릿 생성
		smsTemplate = new Template();
		
		// 불러오기 버튼
		Button btnCall = (Button)findViewById(R.id.btnCall);
		btnCall.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// 인텐트 객체를 생성
				Intent intent = new Intent(SMSTemplate.this, SMSTemplateCall.class);
				// 결과값을 받기 위한 Sub Activity 호출
				startActivityForResult(intent, REQUEST_CODE_TEMPLATECALL);
			}
		});
		
		
		// 템플릿 저장 버튼
		Button btnTemplatSave = (Button)findViewById(R.id.btnTemplateSave);
		btnTemplatSave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				final EditText ed1 =(EditText)findViewById(R.id.editText);
				Builder builder = new AlertDialog.Builder(SMSTemplate.this);
				
				// 텍스트상자에 내용이 없으면
				if(ed1.getText().toString().length()==0){
					builder.setMessage("입력된 내용이 없습니다.");
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
						}
					});
				}
				// 텍스트상자에 내용이 있으면 저장할지 묻는다.
				else{
					builder.setMessage("저장 하시겠습니까?");
					builder.setPositiveButton("취소", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {    
							dialog.cancel();
						}
					});
					builder.setNegativeButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							db = mHelper.getWritableDatabase();
							String _id;
							String msg;
							Date date = new Date();
							SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd (hh:mm:ss)");
							
							_id = df.format(date).toString();
							msg = ed1.getText().toString();
							
							db.execSQL("INSERT INTO smstemplate VALUES ('"+_id+"', '"+msg+"');");
							mHelper.close();
							
							Toast.makeText(SMSTemplate.this, "저장 되었습니다.", Toast.LENGTH_SHORT).show();
						}
					});
				}
				builder.show();
			}
		});
		
		
		
		// 이름
		Button btnName = (Button)findViewById(R.id.btnName);
		btnName.setOnClickListener(new Button.OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##name/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.name_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		
				/*String string ="/##name/#";
				int color =Color.GRAY;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder);*/
			}
		});
		
		// 직위
		Button btnStatus = (Button)findViewById(R.id.btnStatus);
		btnStatus.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##status/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.status_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
			/*	EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##status/#";
				int color =Color.BLUE;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/	
				
			}
		});
		
		// 소속
		Button btnOrganization = (Button)findViewById(R.id.btnOrganization);
		btnOrganization.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##org/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.org_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
				
				/*EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##org/#";
				int color =Color.LTGRAY;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/
				
			}
		});
		
		// 지정
		Button btnCustom = (Button)findViewById(R.id.btnCustom);
		btnCustom.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##custom/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.custom_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
				/*EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##custom/#";
				int color =Color.GREEN;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/
			}
		});
		
		
		
		// 다음 버튼
		Button btnSMSWirteNext = (Button)findViewById(R.id.btnSMSWirteNext);
		btnSMSWirteNext.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				EditText ed1 =(EditText)findViewById(R.id.editText);
				Builder builder = new AlertDialog.Builder(SMSTemplate.this);
				
				// 텍스트상자에 내용이 없으면
				if(ed1.getText().toString().length()==0){
					builder.setMessage("입력된 내용이 없습니다.");
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
						}
					});
				}
				// 텍스트상자에 내용이 있으면 
				else{
					smsTemplate.setOriginalMsg(ed1.getText().toString());
					smsTemplate.analyzeMsg(); // 메시지 분석(분할)
					
					for(int i=0; i<smsTemplate.getAnalyzedMsg().length; i++){
						// custom 있는 경우
						if( smsTemplate.analyzedMsg[i].equals("#custom") ){
							Intent intent = new Intent(getBaseContext(), SMSCustomWord.class);
							startActivityForResult(intent, REQUEST_CODE_SMSCUSTOMWORD);
						}
						// custom 없는 경우
						else {
							Intent intent = new Intent(getBaseContext(), SMSSendActivity.class);
							startActivityForResult(intent, REQUEST_CODE_SMSSEND);
						}
					}
				}
				builder.show();
			}
		});
	}
	
	//현재 입력바이트 보여줌
	private int showBytes(){
		try {
			int length = ed1.getText().toString().getBytes("EUC-KR").length;
			capableByte.setText(length+" / 80 bytes");
			return length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return -1;
	}
	
	
	// onActivityResult()는 결과를 받는 이벤트 핸들러로,
    // startActivityForResult()로 호출한 액티비티가 종료되었을 때 호출된다.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        EditText ed1 = (EditText)findViewById(R.id.editText);
        
        if(requestCode == REQUEST_CODE_TEMPLATECALL) // Sub Activity 호출시 사용된 요청 코드
        {
            if(resultCode == RESULT_OK) // Sub Activity의 결과 코드
            {
                // 받아온 메시지를 액티비티에 표시한다.
                //ed1.setText(data.getStringExtra("originalMsg"));
            	SMSTemplate.smsTemplate.setOriginalMsg(data.getStringExtra("originalMsg"));
            	SMSTemplate.smsTemplate.analyzeMsg();
                ed1.setText("");
        		
        		for(int i =0; i < SMSTemplate.smsTemplate.analyzedMsg.length ; i++){
        			if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#name")){
        				Drawable d = getResources().getDrawable(R.drawable.name);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#status")){
        				Drawable d = getResources().getDrawable(R.drawable.status);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#org")){
        				Drawable d = getResources().getDrawable(R.drawable.org);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#custom")){
        				Drawable d = getResources().getDrawable(R.drawable.custom);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else{
        				ed1.append(SMSTemplate.smsTemplate.analyzedMsg[i]);
        			}
        		}
            }
        }
    }

}

